package com.atguigu.educenter.controller;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.educenter.utils.HttpClientUtils;
import com.atguigu.educenter.utils.WeiXinUtils;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

//微信扫码成功之后会跳转到http://localhost:8150/api/ucenter/wx/callback?code=071MPtGa1WoYVz0qCUIa1BO2im4MPtGd&state=atguigu
//但是想跳转到本地，该端口号为8150，请求地址为/api/ucenter/wx
//这种设置只为了测试，但是实际上只需要布置到项目服务器上
@Controller //不返回数据，值发送请求
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;

    //第一步：扫描成功之后，获取到地址栏上code和state
    @GetMapping("callback")
    public String getWxLogin(String code,String state){//code类似于实际验证码，唯一的值，state原样传递（我写的是什么。传的也是什么）
        try {
            //第二步：获取到的code值，请求微信提供固定的地址，获取到access_token(访问凭证)和openid(每个微信的唯一标识)
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    WeiXinUtils.WEI_XIN_APP_ID,
                    WeiXinUtils.WEI_XIN_APP_SECRET,
                    code
            );
            //使用HTTPClient发送请求，获取到access_token和openid
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            //从accessTokenInfo字符串中获取access_token和openid,将字符串accessTokenInfo转换为Map集合
            //使用json的转换工具gson
            Gson gson=new Gson();
            HashMap<String,String> accessTokenMap = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = accessTokenMap.get("access_token");
            String openid = accessTokenMap.get("openid");

            //判断微信登录的用户是否注册，使用openid
            UcenterMember member=memberService.selectByOpenId(openid);
            if (StringUtils.isEmpty(member)){

            //第三步：获取到access_token和openid，再去请求一个微信地址提供的固定地址，最终可以获取到扫描微信人的信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl,access_token, openid);
            String userInfo = HttpClientUtils.get(userInfoUrl);
            HashMap<String,String> userMap = gson.fromJson(userInfo, HashMap.class);
            String nickname = userMap.get("nickname");//昵称
            String headimgurl = userMap.get("headimgurl");//头像

            //微信用户注册
            member=new UcenterMember();
            member.setAvatar(headimgurl);
            member.setNickname(nickname);
            member.setOpenid(openid);
            memberService.save(member);
            }
            //cookie无法解决跨域问题，使用将token放到地址栏上，
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000?token="+jwtToken;//返回首页
        }catch (Exception e){
            throw new GuliException(20001,"微信登录失败");
        }
    }

    //生成微信的扫描码
    @GetMapping("login")
    public String getWXCode(){
        //微信开发平台授权baseURL，其中%s相当于?代表占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //给redirect_url设置UrlEncoding编码方式，重定向地址，需要进行UrlEncode
        String redirectUrl=WeiXinUtils.WEI_XIN_REDIRECT_URL;
        try {
            redirectUrl= URLEncoder.encode(redirectUrl,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //设置%s里面的值
        String url=String.format(baseUrl, WeiXinUtils.WEI_XIN_APP_ID,redirectUrl,"atguigu");
        //重定向到请求地址
        return "redirect:"+url;
    }
}
